package com.suyafei.mq;

import com.rabbitmq.client.Channel;
import com.suyafei.model.CouponRecordMessage;
import com.suyafei.model.ProductMessage;
import com.suyafei.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @program: suyafei-1024-shop
 * @description
 * @author: luffy
 * @create: 2021-03-22 14:56
 */

@Slf4j
@Component
@RabbitListener(queues = "${mqconfig.stock_release_queue}")
public class ProductStockListener {

    @Autowired
    private ProductService productService;
    /**
     * 重复消费-幂等性
     * 消费失败，重新入队后最大重试次数
     * @param productMessage
     * @param message
     * @param channel
     * @throws IOException
     */
    @RabbitHandler
    public void releaseProductStock(ProductMessage productMessage, Message message, Channel channel) throws IOException {


        log.info("监听到消息:releaseProductStock消息内容{}",productMessage);
        long msgTag = message.getMessageProperties().getDeliveryTag();

        boolean flag = productService.releaseProductStock(productMessage);


        try {
            if (flag) {
                //确认消息消费成功
                channel.basicAck(msgTag, false);
            }else {
                log.error("释放库存失败");
                channel.basicReject(msgTag, true);
            }
        } catch (IOException e) {
            log.error("释放库存记录异常:{},msg:{}", e, productMessage);
            channel.basicReject(msgTag,true);
        }
    }
}
